package com.mobile.collect.activitys;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Size;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.mobile.collect.R;
import com.mobile.collect.camera2.Constant;
import com.mobile.collect.camera2.SquareCameraManager;
import com.mobile.collect.camera2.SquareGLSurfaceView;

import rx.functions.Action1;

public class SquareGLSurfaceViewActivity extends Activity {
    private final String TAG = "SquareGLSurface";
    private SquareGLSurfaceView mGLSurfaceView;
    private int mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
    private SquareCameraManager mCamera;
    int mWidth;
    int mHeight;
    LinearLayout contentLayout;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_photo);

        mGLSurfaceView = new SquareGLSurfaceView(this);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mWidth = dm.widthPixels;
        mHeight = dm.heightPixels;

        Size size = getMatchingSize2();
        contentLayout = findViewById(R.id.contentLayout);
        contentLayout.addView(mGLSurfaceView);


        findViewById(R.id.takePictureBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCamera.takePicture(SquareGLSurfaceViewActivity.this, new Action1<String>() {
                    @Override
                    public void call(String path) {
                        Intent intent = new Intent();
                        intent.putExtra("picPath",path);
                        setResult(Activity.RESULT_OK,intent);
                        finish();
                    }
                });
            }
        });

        mCamera = new SquareCameraManager(this);
        int previewWidth;
        int previewHeight;
        if (null == size) {
            previewWidth = Constant.SYSTEM_PREVIEW_WIDTH;
            previewHeight = Constant.SYSTEM_PREVIEW_HEIGHT;
        } else {
            previewWidth = size.getWidth();
            previewHeight = size.getHeight();
        }
        mGLSurfaceView.initGLSView(mCamera, false, mWidth, mHeight);
        if (!mCamera.openCamera(mCameraId, previewWidth, previewHeight, mHeight, mWidth)) {
            return;
        }
    }


    private Size getMatchingSize2() {
        Size selectSize = null;
        float screenDx = mHeight * 1.0f / mWidth;
        try {

            CameraManager mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
            for (final String cameraId : mCameraManager.getCameraIdList()) {
                CameraCharacteristics cameraCharacteristics = mCameraManager.getCameraCharacteristics(cameraId);
                StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

                Size[] sizes = streamConfigurationMap.getOutputSizes(ImageFormat.JPEG);
                DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); //因为我这里是将预览铺满屏幕,所以直接获取屏幕分辨率
                int deviceWidth = displayMetrics.widthPixels; //屏幕分辨率宽
                int deviceHeigh = displayMetrics.heightPixels; //屏幕分辨率高
                Log.e(TAG, "getMatchingSize2: 屏幕密度宽度=" + deviceWidth);
                Log.e(TAG, "getMatchingSize2: 屏幕密度高度=" + deviceHeigh);
                /**
                 * 循环40次,让宽度范围从最小逐步增加,找到最符合屏幕宽度的分辨率,
                 * 你要是不放心那就增加循环,肯定会找到一个分辨率,不会出现此方法返回一个null的Size的情况
                 * ,但是循环越大后获取的分辨率就越不匹配
                 */
//				for (int j = 1; j < 41; j++) {
                for (int i = 0; i < sizes.length; i++) { //遍历所有Size
                    Size itemSize = sizes[i];
                    Log.e(TAG, "当前itemSize 宽=" + itemSize.getWidth() + "高=" + itemSize.getHeight() + "  比例=" + itemSize.getWidth() * 1.0f / itemSize.getHeight());
                    if (selectSize == null) {
                        selectSize = itemSize;
                    } else {
                        float dx = itemSize.getWidth() * 1.0f / itemSize.getHeight();
                        float selectDx = selectSize.getWidth() * 1.0f / selectSize.getHeight();
                        if (Math.abs(screenDx - dx) < Math.abs(screenDx - selectDx)) {
                            selectSize = itemSize;
                        }
                    }
                }

            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        if (null != selectSize) {
            Log.e(TAG, "getMatchingSize2: 选择的分辨率宽度=" + selectSize.getWidth());
            Log.e(TAG, "getMatchingSize2: 选择的分辨率高度=" + selectSize.getHeight());
        } else {
        }

        return selectSize;
    }


    @Override
    protected void onResume() {
        super.onResume();
        mGLSurfaceView.onResume();
        mCamera.startPreview();
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
//        if (mGLSurfaceView != null) {
//            mGLSurfaceView.onPause();
//        }
//        if (mCamera != null) {
//            mCamera.stopPreview();
//        }

//        if (mGLSurfaceView != null) {
//            mGLSurfaceView.onPause();
//            mGLSurfaceView.unInitGLSView();
//            mGLSurfaceView = null;
//        }
//
//        if (mCamera != null) {
//            mCamera.stopPreview();
//            mCamera.releaseCamera();
//            mCamera = null;
//        }
    }

    @Override
    protected void onDestroy() {
        if (mGLSurfaceView != null) {
            mGLSurfaceView.onPause();
            mGLSurfaceView.unInitGLSView();
            mGLSurfaceView = null;
        }

        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.releaseCamera();
            mCamera = null;
        }
        super.onDestroy();
    }

}
